(function ($) {
  function numMulti(num1, num2) { 
      var baseNum = 0;
      try {
        baseNum += num1.toString().split(".")[1].length;
      } catch (e) {
      }
      try {
        baseNum += num2.toString().split(".")[1].length;
      } catch (e) {
      }
      return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
    };

  function numSub(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    var precision;// 精度
    try {
      baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
      baseNum1 = 0;
    }
    try {
      baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
      baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
  };
  var usercount = {};
  var statu = false;
  getData();
  function getData () {
      $(function () {
      $.ajax({
        url: '../../server/src/sessionStatu.php', 
        dataType: 'json'
      }).then(function (res) {
        if (res.status==1) {
          statu = true;
          usercount = JSON.parse($.cookie("usercount")); 
          $.ajax({
            url: '../../server/src/cartList.php',
            type: 'get',
            dataType: 'json',
            data: { uid:usercount.uid },
          }).then(function (list) {
            initCart(list);
          })
          
        }else{
          $("p.cart_empty_tip").show();
          statu = false;
          var shoppingcart = $.cookie('shoppingcart');
          if (shoppingcart) {
            shoppingcart = JSON.parse(shoppingcart);
          }else{
            shoppingcart = JSON.parse("[]");
          }
          initCart(shoppingcart);
        } 
      })
    })
  }
  
  function initCart (arr) {
    var num = 0;
    var total = 0;
    var oldtotal = 0;
    if (arr.length!=0) { 
      $("#empty-cart").hide();
      $("#not-empty").show();
      $("#shopcart").html('');
      arr.forEach(item=>{
        num += item.num;
        total += numMulti(item.num,item.newprice);
        oldtotal += numMulti(item.num,item.price);
        var allprice = numMulti(item.newprice,item.num);
        var str = `<div class="shopping_con"> <div class="c_meg">  <dl> <dt>
                <a href="detail.html?g_id=${item.g_id}"><img src="${item.img}" width="78" height="78"></a>
              </dt> <dd> <p class="m_tit"><a href="detail.html?g_id=${item.g_id}">${item.title}</a></p>
              <p class="m_tit" style="margin-top:10px;">原价：¥<span id='oldprice'>${item.price}</span></p>
                  </dd> </dl> </div> <div class="c_price">
            <p class="c_price_num">¥<i>${item.newprice}</i></p> </div> <div class="c_quantity">
            <div class="c_amount c_clearfix">  <a href="javascript:;" id="lessBtn">-</a>
                <input type="text" name="amt" data-g_id="${item.g_id}" value="${item.num}"> <a href="javascript:;" id="addBtn">+</a>
            </div>  </div> <div class="c_sum"> <p>¥<i>${allprice}</i></p>
          </div> <div class="c_action"><i class="i_del"`;
        if (statu) {
          str += ` data-cid="${item.cid} "`;
        }
          str += ` data-g_id="${item.g_id}" id="delgood">删除</i>  </div> <div class="c_check">
            <input data-role="product" type="checkbox" checked="checked">  </div> </div>`;
        $("#shopcart").append($(str));
      }) 
      initCheck();
      watchOption(); 
    } 
  }
  function watchOption () { 
    $("div.shopping_con").on('click', 'i#delgood', function(event) { 
        var g_id = $(this).data('g_id');
        if (statu) { 
            $(this).parents("div.shopping_con").remove();
            $.ajax({
              url: '../../server/src/del_cart.php',
              type: 'POST',
              dataType: ' json',
              data: {cid:  $(this).data('cid')},
            }).then(function () {
              getData();
            }) 
            if ($("div.shopping_con").length==0) {
              $("#empty-cart").show();
              $("#not-empty").hide();
            } 
        }else{
          $(this).parents("div.shopping_con").remove();
          var shoppingcart = JSON.parse($.cookie('shoppingcart')); 
          shoppingcart = shoppingcart.filter(item=>{ 
            if (item.g_id!=g_id) {
              return item;
            }
          }) 
          if (shoppingcart.length==0) {
            $.cookie("shoppingcart","",{expires:-1});
            $(this).parents("div.shopping_con").remove();
            $("#empty-cart").show();
            $("#not-empty").hide();
          }else{
            $.cookie("shoppingcart",JSON.stringify(shoppingcart),{expires:10})
           initCheck();
          }
        }
    }); 
    $("div.shopping_con").on('click', '#lessBtn', function(event) {
        var num = parseInt($(this).siblings('input').val());
        if (num>1) { 
          num--;
          var price = Number($(this).parents("div.shopping_con").find('div.c_price p.c_price_num i').text());
          $(this).parents("div.shopping_con").find("div.c_sum i").text(numMulti(num,price)) 
        } 
        var id = $(this).siblings('input').data('g_id');  
        if (statu) {
          var val = parseInt($(this).siblings("input").val());
          if (val>1) {
            val--;
            $(this).siblings("input").val(val); 

            var cid = parseInt($(this).parents("div.shopping_con").find('i#delgood').data('cid'));
            $.ajax({
              url: '../../server/src/less_cart.php',
              type: 'POST',
              dataType: 'json',
              data: {cid: cid},
            }).then(function () {
             initCheck();
            }) 
          }
        }else{
          var shoppingcart = JSON.parse($.cookie('shoppingcart')); 
          var val = parseInt($(this).siblings("input").val());
          shoppingcart = shoppingcart.map(item=>{ 
            if (item.g_id==id) {
              if (item.num>1) {
                item.num --; 
                val--;
                $(this).siblings("input").val(val); 
              }
            }
            return item;
          })
          $.cookie("shoppingcart",JSON.stringify(shoppingcart),{expires:10})
          initCheck();
        }
    }); 
    $("div.shopping_con").on('click', '#addBtn', function(event) { 
        var val = parseInt($(this).siblings("input").val());
        val++;
        $(this).siblings("input").val(val);
        var price = Number($(this).parents("div.shopping_con").find('div.c_price p.c_price_num i').text());
        $(this).parents("div.shopping_con").find("div.c_sum i").text(numMulti(val,price))
        var id = $(this).siblings('input').data('g_id');  
        if (statu) {
          var val = parseInt($(this).siblings("input").val());
          var cid = parseInt($(this).parents("div.shopping_con").find('i#delgood').data('cid'));
          $.ajax({
            url: '../../server/src/add_cart.php',
            type: 'POST',
            dataType: 'json',
            data: {cid: cid},
          }).then(function () {
            initCheck();
          }) 
        }else{
          var shoppingcart = JSON.parse($.cookie('shoppingcart'));
          shoppingcart = shoppingcart.map(item=>{ 
            if (item.g_id==id) { 
                item.num ++; 
            }
            return item;
          })
          $.cookie("shoppingcart",JSON.stringify(shoppingcart),{expires:10})
          initCheck();
        }
    }); 
    $("div#not-empty").on('click', 'input[type=checkbox]', function(event) {
      if ($(this).prop('id')=='selectall') {
        var type = $(this).prop('checked');
        $("div#not-empty").find('input[type=checkbox]').prop("checked",type);
      }
      initCheck();
    });
    // $("div.shopping_con").on('focus', 'input[name=amt]', function() {
    //   console.log($(this))
    // }); 
    $("div.shopping_con").on('blur', 'input[name=amt]', function() {
      var val = Number($(this).val());
       if (statu) { 
        }else{ 
        }
    }); 
  }
  function initCheck () {
    var shoplist = $("div.c_check input:checked").parents("div.shopping_con");
    if (shoplist.length==0) {
      $("p.c_clearfix:first span.c_piece i").text(0);
      $("p.c_clearfix:first span.c_rt i.fs_14").text(0);
      $("p.c_clearfix:eq(1) span.c_rt i.fs_14").text(0);
      $("span.c_paid i").text(0);
    }else {
      var total_num = 0;
      var total_old = 0;
      var total_new = 0;
      for (var i = 0; i < shoplist.length; i++) {
        var item = shoplist[i];
        var oldprice = Number($(item).find('#oldprice').text());
        var num = parseInt($(item).find('input[name=amt]').val());
        var price = Number($(item).find('div.c_price p.c_price_num i').text());
        
        total_num += num;
        total_new += numMulti(num,price);
        total_old += numMulti(num,oldprice);
      }

      $("p.c_clearfix:first span.c_piece i").text(total_num);
      $("p.c_clearfix:first span.c_rt i.fs_14").text(total_old);
      $("p.c_clearfix:eq(1) span.c_rt i.fs_14").text(numSub(total_old,total_new));
      $("span.c_paid i").text(total_new);
    }
  }
})($)

